<?php

/**
 * @Author: wuchenge
 * @Date: 2020-12-05 14:41:23
 * @email: ligui0506@sina.com
 * @descript: 节点控缺点器
 */
namespace App\Admin\v1\Rbac;

use App\Http\Controllers\ApiController;
use App\Libraries\Utils;
use App\Models\Rbac\Node;
use App\Requests\rbac\NodeRequest;
use Illuminate\Http\Request;

class NodeController extends ApiController
{
    public function lists(Request $request)
    {
        $field = ['id', 'name', 'title', 'pid', 'sort'];
        $limit = $request->input('size', config('api.commmon.size'));
        $page  = $request->input('page', config('api.commmon.page'));
        // 节点标题
        $title = $request->input('title', '');

        $where = [
            'nomal' => [],
        ];

        if (!empty($title)) {
            array_push($where['nomal'], [
                'title', 'like', $title . '%',
            ]);
        }

        $result = Node::lists($field, $where, $page, $limit);

        return $this->response($result);
    }

    public function modify(NodeRequest $request)
    {
        // 参数过滤
        $name  = $request->input('name', '');
        $pid   = $request->input('pid', 0);
        $title = $request->input('title', '');
        $sort  = $request->input('sort', 1);
        $nid   = $request->input('id', 0);

        $data = [
            'name'  => $name,
            'pid'   => $pid,
            'title' => $title,
            'sort'  => $sort,
        ];

        if ($nid) {
            // 修改
            if ($nid == $pid) {
                // 父id不能是自己
                return $this->failed();
            }

            // 也不能是自己的子孙级
            $field  = ['id', 'pid'];
            $node   = Node::select($field)->get()->toArray();
            $childs = Utils::childrenID($node, $nid);
            if (in_array($pid, $childs)) {
                return $this->failed();
            }

            $res = Node::where('id', $nid)->update($data);
        } else {
            $res = Node::create($data);
        }

        if ($res) {
            return $this->response();
        }

        return $this->failed();
    }

    public function options()
    {
        $field = ['id', 'name', 'title', 'pid', 'sort'];
        $data  = Node::select($field)
            ->orderBy('sort', 'asc')
            ->get()
            ->toArray();

        $list = Utils::nesting($data);
        return $this->response($list);
    }

    public function delete(Request $request)
    {
        $id  = $request->input('id');
        $ids = explode(',', $id);
        $res = Node::whereIn('id', $ids)->delete();
        if ($res) {
            return $this->response();
        }
        return $this->failed();
    }
}
